#导入requests库
import requests as Request
import re as Response
import json
from outputLog import LogInfo #格式写入Log文件方法

# 定义函数：检查路由
def checkUop(sn):
    try:
        file = open('/vault/data_collection/test_station_config/gh_station_info.json', "rb")
        fileJson = json.load(file)
        url = fileJson['ghinfo']['SFC_URL']
        tsid = fileJson['ghinfo']['STATION_ID']

        params = {'c':'QUERY_RECORD','sn':sn,'p':"UNIT_PROCESS_CHECK","tsid":tsid}
        Response = Request.post(url,data=params,timeout=3)
        Response.raise_for_status()
        Response.encoding = Response.apparent_encoding
        return Response.text
    except:
        return 'CheckUop ERROR'

# 定义函数：测试结果上传MES
def addRecord(sn,result):
    try:
        file = open('/vault/data_collection/test_station_config/gh_station_info.json', "rb")
        fileJson = json.load(file)
        url = fileJson['ghinfo']['SFC_URL']
        tsid = fileJson['ghinfo']['STATION_ID']
        product = fileJson['ghinfo']['PRODUCT']
        test_station_name = fileJson['ghinfo']['GH_STATION_NAME']

        params = {"sn":sn,"c":"ADD_RECORD","result":result,"product":product,"station_id":tsid,"test_station_name":test_station_name}
        Response = Request.post(url,data=params,timeout=5)
        Response.raise_for_status()
        Response.encoding = Response.apparent_encoding
        return Response.text
    except:
        return 'AddRecord ERROR'

# 定义函数：测试Log文件等上传服务器
def uploadFile(filePath):
    try:
        file = open('/vault/data_collection/test_station_config/gh_station_info.json', "rb")
        fileJson = json.load(file)
        url = fileJson['ghinfo']['SFC_URL']
        tsid = fileJson['ghinfo']['STATION_ID']
        product = fileJson['ghinfo']['PRODUCT']
        test_station_name = fileJson['ghinfo']['GH_STATION_NAME']
        # params = {"sn":sn,"c":"ADD_RECORD","result":result,"product":product,"station_id":tsid,"test_station_name":test_station_name}

        params = {'file': open(filePath, 'rb')}
        Response = Request.post(url,files=params,timeout=10)
        Response.raise_for_status()
        Response.encoding = Response.apparent_encoding
        return Response.text
    except:
        return 'UploadFile ERROR'


if __name__ == "__main__":
    LogInfo("--------Start HttpRequest--------")
    result = checkUop("W4XNP22W9V")
    LogInfo(result)
    addResult = addRecord("W4XNP22W9V","PASS")
    LogInfo(addResult)
    uploadResult = uploadFile('/Users/garen.wangq/Desktop/stationTestLog.txt')
    LogInfo(uploadResult)